#
#      Copyright 2011 Miranda, Tom
#       
#       Licensed under the Apache License, Version 2.0 (the "License");
#       you may not use this file except in compliance with the License.
#       You may obtain a copy of the License at
#
#          http://www.apache.org/licenses/LICENSE-2.0
#
#       Unless required by applicable law or agreed to in writing, software
#       distributed under the License is distributed on an "AS IS" BASIS,
#       WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#       See the License for the specific language governing permissions and
#       limitations under the License.
#

import mc, time, sage
from time import strftime
from datetime import date

# This method sets the "normal" metadata that is available from the JSON Object and also sets the metadata that must
# be obtained using additional sagex calls.  The method is therefore fairly time consuming so airingToListItem should be used
# directly whenever possible.
def airingsToListItems(airings, api):
	items = mc.ListItems()

	# Get the recording MediaFiles.
	recordingMediaFiles = api.GetCurrentlyRecordingMediaFiles()
	
	try:
		for airing in airings:
			item = airingToListItem(airing, api)
			
			# See if it's recording, a Favorite or a Manual.
			item = setIsRecording(item, recordingMediaFiles)

			expr = 'IsFavorite(GetAiringForID(%s))' % item.GetProperty('AiringID')
			if api.EvaluateExpression(expr):
				item.SetProperty('IsFavorite', 'True')
		
			expr = 'IsManualRecord(GetAiringForID(%s))' % item.GetProperty('AiringID')
			if api.EvaluateExpression(expr):
				item.SetProperty('IsManualRecord', 'True')
				
			# Set IsShowFirstRun
			expr = 'IsShowFirstRun(GetAiringForID(%s))' % item.GetProperty('AiringID')
			if api.EvaluateExpression(expr):				
				item.SetProperty('IsShowFirstRun', 'True')				
			
			# Set the image.
			item = setThumbUrl(item, api)
			
			items.append(item)
	except Exception,e:
		mc.LogError("SageBoxee: Exception " + str(e))
		mc.LogDebug('SageBoxee: No scheduled recordings.')
		item = mc.ListItem(mc.ListItem.MEDIA_VIDEO_EPISODE)
		item.SetAddToHistory(False)
		item.SetLabel('There are no scheduled recordings.')
		items.append(item)
	if len(items) == 0:
		items.append(createDummyItem())
	return items
	
def airingToListItem(airing, api):

	item = mc.ListItem(mc.ListItem.MEDIA_VIDEO_EPISODE)
	item.SetAddToHistory(False)
		
	# Set the title.
	if (airing.has_key('AiringTitle') and airing['AiringTitle']!=''):
		item.SetLabel(str(airing['AiringTitle']))
		item.SetTVShowTitle(str(airing['AiringTitle']))
	else:
		item.SetLabel('Unknown')
		item.SetTVShowTitle('Unknown')
			
	# AiringID is needed.
	item.SetProperty('AiringID', str(airing['AiringID']))
	
	# Set the background based on category.
	item = sage.setAiringGenreAndBackground(item, airing)

	# Set StationID and ChannelName.
	if (airing.has_key('Channel') and airing['Channel']!=''):
		chan = airing['Channel']
		if(chan.has_key('StationID') and chan['StationID'] != ''):
			item.SetProperty('StationID', str(chan['StationID']))
		else:
			item.SetProperty('StationID', '0')
				
		if(chan.has_key('ChannelName') and chan['ChannelName'] != ''):		
			item.SetProperty('ChannelName', str(chan['ChannelName']))
		else:		
			item.SetProperty('ChannelName', 'Unknown')
			
	# Channel Number	
	if(airing.has_key('AiringChannelNumber')):
		item.SetProperty('AiringChannelNumber', airing['AiringChannelNumber'])
		
	# Set AiringStartTime and AiringEndTime.
	if(airing.has_key('AiringStartTime')):
		startTime = float(airing['AiringStartTime'] // 1000)
		airDate = date.fromtimestamp(startTime)
		airTime = strftime('%H:%M', time.localtime(startTime))
		item.SetProperty('AiringStartTime', str(airDate.month) + '/' + str(airDate.day) + '/' + str(airDate.year) + ' ' + airTime)
		item.SetProperty('AiringStartTimeMillis', str(airing['AiringStartTime']))
			
		# Set AiringEndTime (based on AiringDuration).
		if(airing.has_key('AiringDuration')):
			duration = float(airing['AiringDuration'] // 1000)
			endTime = startTime + duration
			item.SetProperty('AiringEndTime', strftime('%H:%M', time.localtime(endTime)))
			item.SetProperty('AiringEndTimeMillis', str(airing['AiringEndTime']))
			scheduleEndtime = float(airing['ScheduleEndTime'] // 1000)
			item.SetProperty('ScheduleEndTime', strftime('%H:%M', time.localtime(scheduleEndtime)))
			item.SetProperty('ScheduleEndTimeMillis', str(airing['ScheduleEndTime']))
		else:
			item.SetProperty('AiringEndTime', 'Unknown')
			item.SetProperty('AiringEndTimeMillis', '0')
			item.SetProperty('ScheduleEndTime', 'Unknown')
			item.SetProperty('ScheduleEndTimeMillis', '0')
	else:
		item.SetProperty('AiringStartTimeMillis', '0')
		item.SetProperty('AiringEndTimeMillis', '0')
		item.SetProperty('ScheduleEndTimeMillis', '0')
		
	# Show related entries
	if (airing.has_key('Show')):
		show = airing['Show']
		
		# OriginalAirDate
		if(show.has_key('OriginalAiringDate') and show['OriginalAiringDate'] > 0):
			origDate = date.fromtimestamp(float(show['OriginalAiringDate'] // 1000))
			item.SetDate(origDate.year, origDate.month, origDate.day)
		
		# This only works on MediaFile Objects.  For Airing Objects we need an explicit call to IsShowFirstRun().
		#if(show.has_key('IsShowFirstRun') and show['IsShowFirstRun']):
		#	item.SetProperty('IsShowFirstRun', str(show['IsShowFirstRun']))

		# ShowDescription. To retrieve this information in the UI you must use GetProperty(description)
		if (show.has_key('ShowDescription')):		
			item.SetDescription(airing['Show']['ShowDescription'])

	else:
		item.SetProperty('AiringStartTime', 'Unknown')
		item.SetProperty('AiringEndTime', 'Unknown')
		
	# IsWatched
	if(airing.has_key('IsWatched') and airing['IsWatched']):
		item.SetProperty('IsWatched', str(airing['IsWatched']))
		
	# IsHDTV
	if (airing.has_key('IsAiringHDTV') and airing['IsAiringHDTV']):
		item.SetProperty('IsHDTV', 'True')
		
	# ExtraAiringDetails, IsHDTV alternate
	if(airing.has_key('ExtraAiringDetails')):
		item.SetProperty('ExtraAiringDetails', airing['ExtraAiringDetails'])
		if (airing['ExtraAiringDetails'].find('HDTV') != -1):
			item.SetProperty('IsHDTV', 'True')
		
	# Dont Like		
	if(airing.has_key('IsDontLike') and airing['IsDontLike']):
		item.SetProperty('IsDontLike', str(airing['IsDontLike']))
	
	return item
	
def willBeRecorded(item, api):
	expr = 'java_util_HashSet_contains(new_java_util_HashSet(java_util_Arrays_asList(GetScheduledRecordings())), GetAiringForID(%s))' % item.GetProperty('AiringID')
	return api.EvaluateExpression(expr)
	
def createDummyItem():
	item = mc.ListItem(mc.ListItem.MEDIA_VIDEO_EPISODE)
	item.SetAddToHistory(False)
	item.SetLabel('Empty')
	item.SetTVShowTitle('Empty')
	item.SetProperty('IsDummy', 'True')
	return item

# Checks to see if this airing is among those being recorded.
def setIsRecording(item, mediaFiles):
	thisAiringID = item.GetProperty('AiringID')
	for mf in mediaFiles:
		if (mf.has_key('Airing') and mf['Airing'] != ''):
			recAiring = mf['Airing']
			if str(recAiring['AiringID']) == str(thisAiringID):
				item.SetProperty('IsRecording', 'True')
				mc.LogDebug('SageBoxee: Found recording airingID %s' % str(thisAiringID))
				return item
	return item
	
def setThumbUrl(item, api):
	# Set the series image. Set everything possible for the moment until we figure out how to get the SeriesImage to display.
	expr = 'HasSeriesImage(GetShowSeriesInfo(GetShow(GetAiringForID(%s))))' % item.GetProperty('AiringID')
	if api.EvaluateExpression(expr):
		# Get and set the series image.
		seriesImage = api.getSeriesImage(item.GetProperty('AiringID'))
		#seriesImage += "&file=image.png"
		mc.LogDebug("SageBoxee: ThumbImage is SeriesImage " + str(seriesImage)) 
		item.SetProperty('ThumbImage', str(seriesImage))
		item.SetIcon(str(seriesImage))
		item.SetThumbnail(str(seriesImage))
		item.SetImage(0, str(seriesImage))
	else:
		# Get and set the channel logo.
		logoUrl = api.getChannelLogoUrlLarge(item.GetProperty('ChannelName'))
		item.SetProperty('ThumbImage', str(logoUrl))
		mc.LogDebug("SageBoxee: ThumbImage is Logo " + logoUrl)
		item.SetIcon(str(logoUrl))
		item.SetThumbnail(str(logoUrl))
		item.SetImage(0, str(logoUrl))
	return item
	
def isFutureAiring(item):
	nowStruct = time.localtime()
	now = time.mktime(nowStruct) * 1000
	airingStartTime = item.GetProperty('AiringStartTimeMillis')
	airingEndTime = item.GetProperty('AiringEndTimeMillis')
	#print str(now) + " " + str(float(airingStartTime)) + " " + str(float(airingEndTime))
	return now < float(airingEndTime)